﻿using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.Collections.Extensions;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Camc.OutsourceProcession.Authorization.Roles;
using Camc.OutsourceProcession.Organization;

namespace Camc.OutsourceProcession.Authorization.Users
{
    public class UserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory<User, Role>
    {
	    private UserManager _userManagerForOrg;

		public UserClaimsPrincipalFactory(
            UserManager userManager,
            RoleManager roleManager,
            IOptions<IdentityOptions> optionsAccessor)
            : base(
                  userManager,
                  roleManager,
                  optionsAccessor)
		{
			_userManagerForOrg = userManager;
		}

        public override async Task<ClaimsPrincipal> CreateAsync(User user)
        {
	        var claim = await base.CreateAsync(user);

	        var orgsString = (await _userManagerForOrg.GetOrganizationUnitsAsync(user)).Select(c=> OrganizationCodeExtension.GetCompanyCodeFormOrganization(c.Code)).ToArray().JoinAsString(",");
			
	        claim.Identities.First().AddClaim(new Claim("Application_CompanyCode", orgsString));

	        return claim;
        }
	}
}
